﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WarrantyCheck.Resources;
using System.Globalization;
//using Microsoft.Phone.Info;
using BlogRadio;
using Newtonsoft.Json;
using BlogRadio.Models;
using System.Text;
using HtmlAgilityPack;
using System.Diagnostics;
using vservWindowsPhone;

namespace WarrantyCheck
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        #region localizations
        Dictionary<string, string> localizations = new Dictionary<string, string>() { 
            {"aa_ER","ERITREA(Afar)" },

            {"aa_ET","ETHIOPIA(Afar)" },

            {"af_ZA","SOUTH AFRICA(Afrikaans)" },

            {"am_ET","ETHIOPIA(Amharic)" },

            {"ar_BH","BAHRAIN(Arabic)" },

            {"ar_DZ","ALGERIA(Arabic)" },

            {"ar_EG","EGYPT(Arabic)" },

            {"ar_IN","INDIA(Arabic)" },

            {"ar_IQ","IRAQ(Arabic)" },

            {"ar_JO","JORDAN(Arabic)" },

            {"ar_KW","KUWAIT(Arabic)" },

            {"ar_LB","LEBANON(Arabic)" },

            {"ar_LY","LIBYAN ARAB JAMAHIRIYA(Arabic)" },

            {"ar_MA","MOROCCO(Arabic)" },

            {"ar_OM","OMAN(Arabic)" },

            {"ar_QA","QATAR(Arabic)" },

            {"ar_SA","SAUDI ARABIA(Arabic)" },

            {"ar_SD","SUDAN(Arabic)" },

            {"ar_SS","SOUTH SOUDAN(Arabic)" },

            {"ar_SY","SYRIAN ARAB REPUBLIC(Arabic)" },

            {"ar_TN","TUNISIA(Arabic)" },

            {"ar_YE","YEMEN(Arabic)" },

            {"ber_MA","MOROCCO(Berber languages)" },

            {"bn_BD","BANGLADESH(Bengali)" },

            {"bn_IN","INDIA(Bengali)" },

            {"bo_CN","CHINA(Tibetan)" },

            {"bo_IN","INDIA(Tibetan)" },

            {"byn_ER","ERITREA(Bilin)" },

            {"cs_CZ","CZECH REPUBLIC(Czech)" },

            {"cy_GB","UNITED KINGDOM(Welsh)" },

            {"de_AT","AUSTRIA(German)" },

            {"de_BE","BELGIUM(German)" },

            {"de_CH","SWITZERLAND(German)" },

            {"de_DE","GERMANY(German)" },

            {"de_LU","LUXEMBOURG(German)" },

            {"dv_MV","MALDIVES(Dhivehi)" },

            {"dz_BT","BHUTAN(Dzongkha)" },

            {"en_AG","ANTIGUA AND BARBUDA(English)" },

            {"en_AU","AUSTRALIA(English)" },

            {"en_BW","BOTSWANA(English)" },

            {"en_CA","CANADA(English)" },

            {"en_DK","DENMARK(English)" },

            {"en_GB","UNITED KINGDOM(English)" },

            {"en_HK","HONG KONG(English)" },

            {"en_IE","IRELAND(English)" },

            {"en_IN","INDIA(English)" },

            {"en_NG","NIGERIA(English)" },

            {"en_NZ","NEW ZEALAND(English)" },

            {"en_PH","PHILIPPINES(English)" },

            {"en_SG","SINGAPORE(English)" },

            {"en_US","UNITED STATES(English)" },

            {"en_ZA","SOUTH AFRICA(English)" },

            {"en_ZM","ZAMBIA(English)" },

            {"en_ZW","ZIMBABWE(English)" },

            {"es_AR","ARGENTINA(Spanish)" },

            {"es_BO","BOLIVIA, PLURINATIONAL STATE OF(Spanish)" },

            {"es_CL","CHILE(Spanish)" },

            {"es_CO","COLOMBIA(Spanish)" },

            {"es_CR","COSTA RICA(Spanish)" },

            {"es_CU","CUBA(Spanish)" },

            {"es_EC","ECUADOR(Spanish)" },

            {"es_ES","SPAIN(Spanish)" },

            {"es_GT","GUATEMALA(Spanish)" },

            {"es_HN","HONDURAS(Spanish)" },

            {"es_MX","MEXICO(Spanish)" },

            {"es_NI","NICARAGUA(Spanish)" },

            {"es_PA","PANAMA(Spanish)" },

            {"es_PE","PERU(Spanish)" },

            {"es_PR","PUERTO RICO(Spanish)" },

            {"es_PY","PARAGUAY(Spanish)" },

            {"es_SV","EL SALVADOR(Spanish)" },

            {"es_US","UNITED STATES(Spanish)" },

            {"es_UY","URUGUAY(Spanish)" },

            {"es_VE","VENEZUELA, BOLIVARIAN REPUBLIC OF(Spanish)" },

            {"et_EE","ESTONIA(Estonian)" },

            {"fa_IR","IRAN, ISLAMIC REPUBLIC OF(Persian)" },

            {"fi_FI","FINLAND(Finnish)" },

            {"fr_BE","BELGIUM(French)" },

            {"fr_CA","CANADA(French)" },

            {"fr_CH","SWITZERLAND(French)" },

            {"fr_FR","FRANCE(French)" },

            {"fr_LU","LUXEMBOURG(French)" },

            {"gez_ER","ERITREA(Geez)" },

            {"gez_ET","ETHIOPIA(Geez)" },

            {"ha_NG","NIGERIA(Hausa)" },

            {"hsb_DE","GERMANY(Upper Sorbian)" },

            {"ht_HT","HAITI(Haitian)" },

            {"hy_AM","ARMENIA(Armenian)" },

            {"ia_FR","FRANCE(Interlingua (International Auxiliary Language Association))" },

            {"ig_NG","NIGERIA(Igbo)" },

            {"it_IT","ITALY(Italian)" },

            {"iu_CA","CANADA(Inuktitut)" },

            {"kk_KZ","KAZAKHSTAN(Kazakh)" },

            {"km_KH","CAMBODIA(Central Khmer)" },

            {"ku_TR","TURKEY(Kurdish)" },

            {"lb_LU","LUXEMBOURG(Luxembourgish)" },

            {"li_NL","NETHERLANDS(Limburgan)" },

            {"lo_LA","LAO PEOPLE'S DEMOCRATIC REPUBLIC(Lao)" },

            {"my_MM","MYANMAR(Burmese)" },

            {"nds_DE","GERMANY(Low German)" },

            {"nds_NL","NETHERLANDS(Low German)" },

            {"nl_BE","BELGIUM(Dutch)" },

            {"nl_NL","NETHERLANDS(Dutch)" },

            {"nr_ZA","SOUTH AFRICA(South Ndebele)" },

            {"nso_ZA","SOUTH AFRICA(Pedi)" },

            {"om_ET","ETHIOPIA(Oromo)" },

            {"om_KE","KENYA(Oromo)" },

            {"os_RU","RUSSIAN FEDERATION(Ossetian)" },

            {"ps_AF","AFGHANISTAN(Pushto)" },

            {"ro_RO","ROMANIA(Romanian)" },

            {"ru_UA","UKRAINE(Russian)" },

            {"rw_RW","RWANDA(Kinyarwanda)" },

            {"sd_IN","INDIA(Sindhi)" },

            {"shs_CA","CANADA(Shuswap)" },

            {"sid_ET","ETHIOPIA(Sidamo)" },

            {"so_DJ","DJIBOUTI(Somali)" },

            {"so_ET","ETHIOPIA(Somali)" },

            {"so_KE","KENYA(Somali)" },

            {"so_SO","SOMALIA(Somali)" },

            {"sq_MK","MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF(Albanian)" },

            {"sr_ME","MONTENEGRO(Serbian)" },

            {"sr_RS","SERBIA(Serbian)" },

            {"ss_ZA","SOUTH AFRICA(Swati)" },

            {"st_ZA","SOUTH AFRICA(Southern Sotho)" },

            {"sv_FI","FINLAND(Swedish)" },

            {"sv_SE","SWEDEN(Swedish)" },

            {"ta_IN","INDIA(Tamil)" },

            {"ta_LK","SRI LANKA(Tamil)" },

            {"te_IN","INDIA(Telugu)" },

            {"tg_TJ","TAJIKISTAN(Tajik)" },

            {"th_TH","THAILAND(Thai)" },

            {"tig_ER","ERITREA(Tigre)" },

            {"ti_ER","ERITREA(Tigrinya)" },

            {"ti_ET","ETHIOPIA(Tigrinya)" },

            {"tk_TM","TURKMENISTAN(Turkmen)" },

            {"tl_PH","PHILIPPINES(Tagalog)" },

            {"tn_ZA","SOUTH AFRICA(Tswana)" },

            {"tr_CY","CYPRUS(Turkish)" },

            {"tr_TR","TURKEY(Turkish)" },

            {"ts_ZA","SOUTH AFRICA(Tsonga)" },

            {"tt_RU","RUSSIAN FEDERATION(Tatar)" },

            {"ug_CN","CHINA(Uighur)" },

            {"uk_UA","UKRAINE(Ukrainian)" },

            {"unm_US","UNITED STATES(Unami)" },

            {"ur_IN","INDIA(Urdu)" },

            {"ur_PK","PAKISTAN(Urdu)" },

            {"uz_UZ","UZBEKISTAN(Uzbek)" },

            {"ve_ZA","SOUTH AFRICA(Venda)" },

            {"vi_VN","VIET NAM(Vietnamese)" },

            {"wae_CH","SWITZERLAND(Walser)" },

            {"wal_ET","ETHIOPIA(Wolaytta)" },

            {"wa_BE","BELGIUM(Walloon)" },

            {"wo_SN","SENEGAL(Wolof)" },

            {"xh_ZA","SOUTH AFRICA(Xhosa)" },

            {"yi_US","UNITED STATES(Yiddish)" },

            {"yo_NG","NIGERIA(Yoruba)" },

            {"yue_HK","HONG KONG(Yue Chinese)" },

            {"zh_CN","CHINA(Chinese)" },

            {"zh_HK","HONG KONG(Chinese)" },

            {"zh_SG","SINGAPORE(Chinese)" },

            {"zh_TW","TAIWAN(Chinese)" },

            {"zu_ZA","SOUTH AFRICA(Zulu)" },
        };
        private KeyValuePair<string, string> selectedItem;
        private bool warrantyDone;
        private bool imeiDone;
        private bool adsLoaded;
        #endregion

        public MainPage()
        {
            InitializeComponent();

            lpCountry.ItemsSource = localizations.OrderBy(t => t.Value).ToList();
            var locale = CultureInfo.CurrentCulture.Name.Replace("-", "_");
            lpCountry.SelectedItem = localizations.Single(t => t.Key == locale);
            EmbedVserV();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                tbImei.Text = "357297054526950";
            }

            if (adsLoaded)
            {
                UIElement ads = null;
                foreach (var element in LayoutRoot.Children)
                {
                    if (element.GetType().ToString().Contains("AdsV2"))
                    {
                        ads = element;
                    }
                }
                if (ads != null)
                {
                    LayoutRoot.Children.Remove(ads);
                }
            }
        }

        private void btnCheck_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            selectedItem = (KeyValuePair<string, string>)lpCountry.SelectedItem;
            var locale = selectedItem.Key;
            var webClientWarranty = API.GetWebClient();
            webClientWarranty.DownloadStringAsync(new Uri(String.Format("http://www.nokia.com/wal/care/warranty/?r=true&locale={0}&productId=&inst=&deviceId={1}",locale,tbImei.Text),UriKind.Absolute));
            webClientWarranty.DownloadStringCompleted += webClientWarranty_DownloadStringCompleted;

            var requestUri = new Uri(String.Format("http://www.imei.info/?imei={0}", tbImei.Text), UriKind.Absolute);
            CookieContainer cookieJar = new CookieContainer();
            cookieJar.Add(requestUri, new Cookie("sessionid", "dbc7151b63fb1a2b9469bb6688f31698", "/", ".imei.info"));
            var webClient = API.GetWebClient( cookieJar);

            webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
            webClient.DownloadStringAsync(requestUri);
            tbDeviceName.Text = "";
            tbResult.Text = "";
            TurnOnIndicator();
        }

        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(e.Result);
                var dane = doc.DocumentNode.SelectSingleNode("//div[@id='dane']");
                if (dane != null)
                {
                    var dotsFirst = dane.SelectSingleNode("./p[@class='dots first']");
                    var deviceName = dotsFirst.ChildNodes[1].InnerText;
                    tbDeviceName.Text = HttpUtility.HtmlDecode(deviceName).Trim();
                }
                else
                {
                    tbDeviceName.Text = "Try again!";
                    //if (Debugger.IsAttached)
                    //{
                    //MessageBox.Show("");
                    //}
                }
            }
            else
            {
                //tbDeviceName.Text = "Try again!";
                MessageBox.Show(e.Error.Message);
            }
            imeiDone = true;
            TurnOffIndicator();
        }

        private void TurnOnIndicator()
        {
            imeiDone = false;
            warrantyDone = false;
            busyIndicator.IsRunning = true;
        }

        //void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        //{
        //    if (e.Error == null)
        //    {
        //        HtmlDocument doc = new HtmlDocument();
        //        doc.LoadHtml(e.Result);
        //        var dane = doc.DocumentNode.SelectSingleNode("//div[@id='dane']");
        //        if (dane != null)
        //        {
        //            var dotsfirst = dane.SelectSingleNode("./p[@class='dots first']");
        //            MessageBox.Show(dotsfirst.InnerHtml);
        //        }
        //    }
        //    else
        //    {
        //        MessageBox.Show(e.Error.Message);
        //    }
        //    imeiDone = true;
        //    TurnOffIndicator();
        //}

        private void TurnOffIndicator()
        {
            if (imeiDone && warrantyDone)
                busyIndicator.IsRunning = false;
        }

        void webClientWarranty_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (API.CheckWebClient(e))
            {
                var warranty = JsonConvert.DeserializeObject<Models.Warranty>(e.Result);

                switch (warranty.warrantyStatus)
                {
                    case "Y":
                        tbResult.Text = AppResources.InTheWarranty;
                        tbResult.Foreground = 0xff049c00.ToSolidColorBrush();
                        break;
                    case "N":
                        tbResult.Text = AppResources.OutOfWarranty;
                        tbResult.Foreground = 0xffffa00a.ToSolidColorBrush();
                        break;
                    case "invalid_device_id":
                        tbResult.Text = AppResources.InvalidIMEI;
                        tbDeviceName.Text = AppResources.InvalidIMEI;
                        tbResult.Foreground = 0xffff0000.ToSolidColorBrush();
                        break;

                }
                
            }
            warrantyDone = true;
            busyIndicator.IsRunning = false;
        }

        private static void RateApp()
        {
            int ratecount = Convert.ToInt32(Config.GetValue("ratecount"));
            if (ratecount != 1)
            {
                Config.SetValue("ratecount", (ratecount + 1).ToString());
                Application.Current.Terminate();
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {

                    CustomMessageBox messageBox = new CustomMessageBox()
                    {
                        Caption = AppResources.RateApp,
                        Message = AppResources.RateAppMessage,
                        LeftButtonContent = AppResources.Rate5Star,
                        RightButtonContent = AppResources.Later,
                    };

                    messageBox.Dismissed += (s1, e1) =>
                    {
                        switch (e1.Result)
                        {
                            case CustomMessageBoxResult.LeftButton:
                                API.RateApp();
                                Config.SetValue("ratecount", (ratecount + 1).ToString());
                                break;
                        }
                        Application.Current.Terminate();
                    };

                    messageBox.Show();
                });
            }
        }
        private static void ExitApp()
        {
            if (MessageBox.Show(AppResources.ExitAppMessage, AppResources.ExitApp, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RateApp();
            }
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            ExitApp();
            base.OnBackKeyPress(e);
        }

        private void EmbedVserV()
        {
            VservAdControl VAC = VservAdControl.Instance;
            VAC.VservAdClosed += VACCallback_OnVservAdClosing;
            VAC.VservAdError += VACCallback_OnVservAdNetworkError;
            VAC.VservAdNoFill += VAC_VservAdNoFill;
            VAC.DisplayAd("226faa93", LayoutRoot);//fbf6397e
        }

        private void VAC_VservAdNoFill(object sender, EventArgs e)
        {
            //CreateAppBar();
            adsLoaded = true;
        }

        private void VACCallback_OnVservAdNetworkError(object sender, EventArgs e)
        {
        }

        private void VACCallback_OnVservAdClosing(object sender, EventArgs e)
        {
            //CreateAppBar();
            adsLoaded = true;
        }
    }
}